import { useAuthMenu } from "../../store/authMenu";
// 引入 views 文件夹下所有 vue 文件
import { OPEN_DYNAMIC_ROUTER } from "../../config/config";
import { flatRouter, generateDynamicRouterMenu } from "../../utils/menuUtil";
import { dynamicRouter } from "../../dynamicRouter/index";
import router from "@/router/index";

const modules = import.meta.glob("@/views/**/*.vue");

const processRouter = (routerList) => {
  if (!routerList || routerList.length === 0) {
    return;
  }
  routerList.forEach((item) => {
    if (item.component) {
      const path = `/src/views${item.component}.vue`;
      item.component = modules[path];
    }
    //将路由添加到layout下
    router.addRoute("layout", item);
    processRouter(item.children);
  });
};

//初始化动态路由
export const initDynamicRouter = () => {
  const authMenu = useAuthMenu();
  if (!OPEN_DYNAMIC_ROUTER) {
    return;
  }
  if (authMenu.dynamicMenuList) {
    return;
  }
  //获取动态路由
  const routerList = dynamicRouter;
  //处理路由组件component
  processRouter(routerList);

  const flatMenuList = flatRouter(routerList);
  // 注册动态路由
  flatMenuList.forEach((item) => {
    if (item.meta?.isFull && router.hasRoute(item.name)) {
      router.removeRoute(item.name);
      router.addRoute(item);
    }
  });
  //生成动态菜单
  const menu = generateDynamicRouterMenu(routerList);
  authMenu.dynamicMenuList = menu;
  authMenu.authMenuList.push(...menu);
};
